﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using BuXiaChu.OrderDishes.BLL.WebRuntime;
using BuXiaChu.OrderDishes.BLL;
using System.IO;
using BuXiaChu.OrderDishes.BLL.Utility;

namespace BuXiaChu.OrderDishes.Web.Admin.ImageShow
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Get : HttpHandlerBase, IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            base.Init(context);

            Dishes(Request.QueryString["id"]);
        }

        public void Dishes(string id)
        {
            var image = ImageShowManage.Dishes.GetImageFromCache(id);
            if (image.Length <= 0)
            {
                WriteDefaultImage();
            }
            WriteImage(image);
        }

        private void WriteImage(byte[] image)
        {
            if (image.Length > 0)
            {
                Response.ContentType = "application/octet-stream";
                Response.BinaryWrite(image);
                Response.End();
            }
        }

        private void WriteDefaultImage()
        {
            var fileName = IOUtility.GetRootedFilePath(@"Images\default.png");
            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                int len = int.Parse(stream.Length.ToString());
                byte[] array = new byte[len];

                stream.Read(array, 0, len);

                WriteImage(array);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
